package com.tanhua.api.mongdb;

import com.tanhua.domain.mogo.UserLocation;
import com.tanhua.domain.vo.UserLocationVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service
public class UserLocationApiImpl implements UserLocationApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void findUser(Long userId,double y_longitude, double x_latitude, String addrStr) {

        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        if(userLocation==null){
            //该用户没有上传过地理位置--新增
            userLocation=new UserLocation();
            userLocation.setUserId(userId);
            GeoJsonPoint geoJsonPoint = new GeoJsonPoint(y_longitude,x_latitude);
            userLocation.setLocation(geoJsonPoint);
            userLocation.setAddress(addrStr);
            userLocation.setUpdated(System.currentTimeMillis());
            mongoTemplate.insert(userLocation);
        }else{
            //该用户之前上传过地理位置--修改
            GeoJsonPoint geoJsonPoint = new GeoJsonPoint(y_longitude,x_latitude);
            Update update = new Update();
            update.set("address",addrStr);
            update.set("location",geoJsonPoint);
            update.set("updated",System.currentTimeMillis());
            mongoTemplate.upsert(query,update,UserLocation.class);
        }

    }

    @Override
    public List<UserLocationVo> search(Long userId, Integer distance) {
        //先查询自己的地理信息
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        //设定距离 /1000 按公里查
        Distance jl = new Distance(distance / 1000, Metrics.KILOMETERS);
        //距离划分半径
        Circle circle=new Circle(userLocation.getLocation(),jl);
        // 根据划分出来的半径做附近人的搜索
        Query query2=new Query(Criteria.where("location").withinSphere(circle));

        //根据圆半径搜出来的所有用户
        List<UserLocation> userLocationList = mongoTemplate.find(query2, UserLocation.class);

        // GeoJsonPoint--我们自己创建的对象---实现序列化
        List<UserLocationVo> userLocationVos = UserLocationVo.formatToList(userLocationList);
        return  userLocationVos;


    }

}
